package com.fingard.dsp.bank.directbank.allinpay03;

import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.allinpay03.util.AESUtil;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.helpers.YBTHelper;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.security.PrivateKey;
import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class AllInPay03BatPayRec extends AllInPay03Base implements IBatPayRec {
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req1988.reqHeader);
        retAts.reqSeqID = p_req1988.reqBatchNO;
        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req1988.ownAct, "");
            if (actItem == null) {
                retAts.respCode = "0";
                retAts.respInfo = "未找到账号:[" + p_req1988.ownAct + "]商户配置信息!";
                retAts.reqSeqID = p_req1988.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = FailCode.E9981;
                retAts.writeRetToATS();
                return retAts;
            }
            Date tmpDateNow = getDayCutTime(p_req1988.getPayDateTime());
            // 代收付文件内容
            StringBuilder sbFileContent = new StringBuilder();
            String totalAmt = StringHelper.amountMultiply100(p_req1988.totalAmt);
            String tmpReqHeader = MessageFormat.format("{0},{1},{2},{3},{4},{5},{6}", "X", actItem.merchantId, p_req1988.totalNum, totalAmt, "1", "6002", "1");
            sbFileContent.append(tmpReqHeader);
            while (p_req1988.readRecord()) {
                if (sbFileContent.length() > 0) {
                    sbFileContent.append("\n");
                }

                String oppAct = p_req1988.readedDetail.recAct;
                String oppName = p_req1988.readedDetail.recName;
                String cellPhone = p_req1988.readedDetail.cellPhone;
                String payAmt = StringHelper.amountMultiply100(p_req1988.readedDetail.payAmount);
                String idNum = p_req1988.readedDetail.certNum;
                String summary = p_req1988.readedDetail.askNumber+"+"+p_req1988.readedDetail.memo;

                // 明细信息:序列号(20位)|客户账号|客户账号户名|交易金额(单位:分)|借贷标志(1借,2贷)|摘要|是否银保通保单(1是,0否)|保单号|业务类型|委托代扣代付协议号\n
                String tmpReqBodyDetail = MessageFormat.format("{0},{1},{2},{3},{4},{5},{6},{7},{8}", oppName, cellPhone, idNum, oppAct, payAmt, summary.length() > 64 ? summary.substring(0, 64) : summary, ",", ",", ",");
                sbFileContent.append(tmpReqBodyDetail);
            }
            WriteBankLogLn2("批次文件内容:\r\n" + sbFileContent.toString());
            String tmpPaySendDate = Format.Date8Format.format(tmpDateNow);
            String tmpBatSeqNo = YBTHelper.getBatSeqNo(getTempFileDirectory(tmpDateNow), 5);
            String tmpUploadFileName = "XJFF_" + actItem.merchantId + "_" + tmpPaySendDate + "_" + tmpBatSeqNo + ".req";
            String tmpLocalMarkPath = getTempFileDirectory(tmpDateNow) + File.separator + tmpUploadFileName;
            WriteBankLogLn2("批次文件保存本机路径: " + tmpLocalMarkPath);
            if (FileHelper.existFile(tmpLocalMarkPath)) {
                retAts.respCode = "0";
                retAts.respInfo = "本地批次文件已上传,请勿重复上传!";
                retAts.reqSeqID = p_req1988.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = FailCode.E9981;
                retAts.writeRetToATS();
                return retAts;
            }
            FileHelper.writeFile(tmpLocalMarkPath, sbFileContent.toString(), getCharset());
            String remark  = p_req1988.abstractATS+"+"+p_req1988.memo;
            Map<String, Object> bizMap = prepareData(p_req1988, sbFileContent.toString(), actItem,remark);
            String result = doSendData("appwallet", "bussservice/batchAccountTransfer", bizMap, actItem);
            if (result != null) {
                JSONObject resObj = JSONObject.parseObject(result);
                String subCode = resObj.getString("subCode");
                String subMsg = resObj.getString("subMsg");
                if ("000000".equals(subCode)) {
                    retAts.respCode = "0";
                    retAts.respInfo = "上传成功";
                    retAts.transState = "Uploaded";
                    retAts.payInfoCode = "I4001";
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = subMsg;
                    retAts.transState = "BatchFailed";
                    retAts.payInfoCode = "E9999";
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeRetToATS();
        return retAts;
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req1998.reqHeader);
        retAts.reqSeqID = p_req1998.reqBatchNO;
        try {
            ActSetItem actItem = this.getBankConfig().getActSetItem(p_req1998.ownAct, "");
            if (actItem == null) {
                retAts.respCode = "-1";
                retAts.respInfo = "未找到账号:[" + p_req1998.ownAct + "]商户配置信息!";
                retAts.writeAfterDetail();
                return retAts;
            }
            Map<String, Object> bizContent = new HashMap<String, Object>();
            bizContentPut(bizContent, "custId", actItem.merchantId);
            bizContentPut(bizContent, "batchNo", actItem.merchantId + p_req1998.reqBatchNO);
            String date = Format.Date8Format.format(p_req1998.getBgnDateTime());
            bizContentPut(bizContent, "beginDate", date);
            bizContentPut(bizContent, "endDate", Format.Date8Format.format(new Date()));
            //bizContentPut(bizContent, "fileStatus", "1");
            bizContentPut(bizContent, "txnCode", "300030");

            String retStr = doSendData("paycenter", "appservice/getBatchAccountTransferDetail", bizContent, actItem);
            if (retStr != null) {
                JSONObject resObj = JSONObject.parseObject(retStr);
                String subCode = resObj.getString("subCode");
                String subMsg = resObj.getString("subMsg");
                if ("000000".equals(subCode)) {
                    String data = resObj.getString("data");
                    JSONObject jsondata = JSONObject.parseObject(data);
                    String currAnt = jsondata.getString("currcnt");
                    if ("1".equals(currAnt)) {
                        JSONObject dataList = (JSONObject) jsondata.getJSONArray("dataList").get(0);
                        if ("0".equals(dataList.getString("fileStatus")) ||"1".equals(dataList.getString("fileStatus"))) {
                            Map<String, Object> bizContents = new HashMap<String, Object>();
                            //bizContentPut(bizContent, "fileName", fileName);
                            bizContentPut(bizContents, "batchNo", actItem.merchantId + p_req1998.reqBatchNO);
                            String retStrs = doSendData("appwallet", "appservice/downloadBatchAccountTransferDetail", bizContents, actItem);
                            JSONObject resObjs = JSONObject.parseObject(retStrs);
                            JSONObject jsondatas = JSONObject.parseObject(resObjs.getString("data"));
                            String randKey = (String) jsondatas.get("randKey");
                            String contentEnced = (String) jsondatas.get("content");
                            PrivateKey privateKey = getRSAPrivateKey(actItem.ownKeyStorePath);
//
                            Cipher cipher = Cipher.getInstance("RSA");
                            cipher.init(Cipher.DECRYPT_MODE, privateKey);
                            String pwd = new String(cipher.doFinal(toByteArray(randKey)));
                            WriteBankLogLn2("pwd:" + pwd);
                            String content = AESUtil.decrypt(toByteArray(contentEnced), new SecretKeySpec(AESUtil.getBaseFromRandKey(pwd), AESUtil.KEY_ALGORITHM));
                            WriteBankLogLn2("批次结果文件内容:" + content);
                            if (StringHelper.hasAnyChar(content)) {
                                retAts.respCode = "0";
                                retAts.reqSeqID = p_req1998.reqBatchNO;

                                StringReader strReader = new StringReader(content);
                                BufferedReader tmpReader = new BufferedReader(strReader);

                                while (true) {
                                    String eachline = tmpReader.readLine();
                                    if (StringHelper.isNullOrEmpty(eachline)) {
                                        break;
                                    }
                                    String[] str = eachline.split(",");
                                    RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                                    tmpRetDetail.recAct = str[3];
                                    tmpRetDetail.recName = str[0];
                                    tmpRetDetail.postScript = str[5].split("\\+")[0];
                                    tmpRetDetail.payAmount = StringHelper.amountDivide100(str[4]);
                                    tmpRetDetail.payInfoCode = str[13];
                                    tmpRetDetail.memo = str[13];
                                    tmpRetDetail.result = str[12];
                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                            } else {
                                retAts.respCode = "-1";
                                retAts.respInfo = "批次号：" + p_req1998.reqBatchNO + "回盘文件内容为空!";
                            }
                        } else if ("2".equals(dataList.getString("fileStatus"))) {
                            retAts.respCode = "0";
                            retAts.respInfo = "批次文件处理中!";
                        } else {
                            retAts.respCode = "0";
                            retAts.respInfo = "批次处理失败!";
                        }
                    } else {
                        if (canBeNotExist(p_req1998, retAts, 45)) {
                            retAts.respCode = "0";
                            retAts.respInfo = "批次记录不存在";
                            retAts.transState = PaymentState.FAIL_Batch;
                            retAts.payInfoCode = "E1302";
                            retAts.writeAfterDetail();
                            return retAts;
                        }
                    }
                } else {
                    retAts.respCode = "0";
                    retAts.respInfo = subMsg;
                    retAts.transState = subCode;
                    retAts.payInfoCode = subCode;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeAfterDetail();
        return retAts;
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return null;
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return null;
    }
}
